#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import logging

import pika

logger = logging.getLogger(__name__)

class RPCWorker(object):
    EXCHANGE_TYPE = 'direct'
    EXCHANGE_TPL = '{}.rpc.exchange'
    ROUTINGKEY_TPL = '{}-rpc-queue'

    def __init__(self, name, amqp_url):
        self._name = name
        self._url = amqp_url
        self._exchange = self.EXCHANGE_TPL.format(self._name)
        self._routing_key = self.ROUTINGKEY_TPL.format(self._name)

        self._conn = pika.BlockingConnection(pika.URLParameters(amqp_url))
        self._chann = self._conn.channel()
        self._chann.exchange_declare(exchange=self._exchange, exchange_type='direct')
        resutl = self._chann.queue_declare()
        self._queue_name = resutl.method.queue
        self._chann.basic_qos(prefetch_count=1)
        self._chann.queue_bind(exchange=self._exchange,
                              queue=self._queue_name,
                              routing_key=self._routing_key)
        self._chann.basic_consume(self.on_request, self._queue_name)

    def start(self):
        self._chann.start_consuming()

    def on_request(self, ch, method, props, body):
        task = json.loads(body.decode('utf-8'))

        logger.info('task => %s', task)
        task_result = self.do_task(task)

        self._chann.basic_publish(exchange=self._exchange, routing_key=props.reply_to,
        properties=pika.BasicProperties(correlation_id=props.correlation_id), body=task_result)
        self._chann.basic_ack(delivery_tag=method.delivery_tag)

    def do_task(self, task):
        raise NotImplementedError()
